/**
 * 
 */
package com.baidu.yun.push.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.icbc.cc.api.AppCommonUtils;
import com.icbc.cte.base.CTEConstance;
import com.icbc.cte.base.TranFailException;
import com.icbc.cte.logging.Log;
import com.icbc.cte.logging.LogFactory;
import com.icbc.ctp.core.IContext;
import com.icbc.ctp.core.annotations.Input;
import com.icbc.ctp.core.annotations.JavaStep;
import com.icbc.ctp.core.annotations.Output;
import com.icbc.ctp.core.impl.OperationStep;

/**
 * TODO 类的描述：。 
 * <pre>
 *
 * </pre>
 *
 * <pre>
 * modify by Jiahy on 2016-6-17
 *    fix->1.
 *         2.
 * </pre> 
 */
@Input(name = {  "msgTitle", "msgCont", "pushTime","msgType","divType","msgUrl" }, type = {  "String", "String", "String", "String", "String", "String" }, description = { "", "","", "","", "", "" }, mustInput = { true, true, true,true, true, true}, isVariable = { true, true, true,true, true, true })
@Output(name = { "pushId" }, type = { "String"}, description = { ""})
@JavaStep
public class PushMsg extends OperationStep{
	
	private static Log log = LogFactory.getCtpLog(PushMsg.class);
	
	@Override
	protected int execute(IContext context)  {
		JGPushUtil pushUtil=new JGPushUtil();
		try {
		String msgTitle = (String) getInputValue(context, "msgTitle");
		String msgCont = (String) getInputValue(context, "msgCont");
		String pushTime = (String) getInputValue(context, "pushTime");
		String msgType = (String) getInputValue(context, "msgType");
		int divType = Integer.parseInt((String)getInputValue(context, "divType")) ;
		String msgUrl = (String) getInputValue(context, "msgUrl");
		
//		long pushID=System.currentTimeMillis()/1000;
//		JSONObject content = new JSONObject(); 
		JSONObject custom_content = new JSONObject(); 
//		JSONObject aps = new JSONObject();
		try {
//			aps.put("sound", "default");
//			custom_content.put("pushId", pushID);
			custom_content.put("pushTime", pushTime);
			custom_content.put("type", "0");
			custom_content.put("msgType", msgType);
			custom_content.put("msgUrl", msgUrl);
//			custom_content.put("chanelId", "");
//			content.put("aps", aps);
//			content.put("title", msgTitle);
//			content.put("msgCont", msgCont);
//			content.put("msgTitle", msgTitle);
//			content.put("description", msgCont);
//			content.put("custom_content", custom_content);
		} catch (JSONException e) {
			log.error(e);
		}
//		String Msg=content.toString();
//		
//		String msgIds = pushAllMessage(Msg,1,divType,pushTime);
		String msgIds="";
		if(divType==3){
			msgIds=pushUtil.sendToAllAndroid(msgTitle, msgTitle, msgCont, custom_content.toString(),pushTime.substring(0, 19));
		}else{
			msgIds=pushUtil.sendToAllIos(msgTitle, msgTitle, msgCont, custom_content.toString(),pushTime.substring(0, 19));
		}
		
		if(msgIds !=null && !"".equals(msgIds)){
			JSONObject obj=new JSONObject();
			try {
				obj.put("msgTitle", msgTitle);
				obj.put("msgCont", msgCont);
				obj.put("pushtime", pushTime);
				obj.put("msgType", msgType);
				String 	result = AppCommonUtils.excuteOp(obj.toString(), "insert_all_msg");
				log.info(" insert_all_msg retMsg result: 参数:"+obj+"结果:"+result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		setOutputValue(context, "pushId", msgIds);
		
		} catch (TranFailException e) {
			log.error(e);
		}
		return 0;
	}
	/**
	* 初始化百度推送
	* @return
	*/
	public static BaiduPushClient initPushClient(String apiKey,String secretKey ){

		PushKeyPair pair = new PushKeyPair(apiKey,secretKey);
	
		BaiduPushClient pushClient = new BaiduPushClient(pair,BaiduPushConstants.CHANNEL_REST_URL);
		pushClient.setChannelLogHandler(new YunLogHandler() {

			@Override
			public void onHandle(YunLogEvent arg0) {
			System.out.println(arg0.getMessage());

			}
			});
			return pushClient;
			}
	//广播
	public static String pushAllMessage(String content,int pushType,int divType,String pushDate){
				String apiKey="";
				String secretKey="";
				String deployStatus=null;
				if(divType==4){
					deployStatus= CTEConstance.getEnvProperty("deployStatus");
					apiKey = CTEConstance.getEnvProperty("apiKeyIos");
					secretKey = CTEConstance.getEnvProperty("secretKeyIos"); 
				}else if(divType==3){
					apiKey = CTEConstance.getEnvProperty("apiKey");
					secretKey = CTEConstance.getEnvProperty("secretKey"); 
				}
		
			BaiduPushClient client=initPushClient(apiKey,secretKey);
			
			PushMsgToAllRequest request=new PushMsgToAllRequest();
			
			request.setMessage(content);
			//devType 1:web 2:pc 3:android 4:ios 5:wp
			request.setDeviceType(divType);
			//pushType 0-置送消息 1-置送通知
			request.setMessageType(pushType);
			
			//推送时间
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Date date=null;
			long pushTime=System.currentTimeMillis()/1000+300;
			try {
				Calendar cal=Calendar.getInstance();
				long time=cal.getTimeInMillis()/1000+300;
				date=sdf.parse(pushDate);
				long pushdate=(int)date.getTime()/1000;
				System.err.println(time);
				System.err.println(pushdate);
				if(time<=pushdate){
					pushTime=pushdate;
				}
			} catch (ParseException e1) {
				log.error(e1);
			}
			
			request.setSendTime(pushTime);

			if(divType==4){
				request.setDeployStatus(Integer.parseInt(deployStatus));//ios推送状态    1-开发 2-生产  默认null
			}
			String msgId="";
			try {
				PushMsgToAllResponse response=client.pushMsgToAll(request);
				
				QueryMsgStatusRequest queryRequest=new QueryMsgStatusRequest();
				queryRequest.setMsgId(response.getMsgId());
				
				QueryMsgStatusResponse  queryResponse=client.queryMsgStatus(queryRequest);
				List<MsgSendInfo> list=queryResponse.getMsgSendInfos();
				MsgSendInfo info=list.get(0);
				int sum=info.getSuccessCount();
				System.out.println(response.getMsgId());
				System.out.println(sum);
				msgId=response.getMsgId();
			} catch (PushClientException e) {
				log.error(e);
			} catch (PushServerException e) {
				log.error(e);
			}

			return msgId;

	}
	
}
